import { ref, reactive } from 'vue';
import { addRecipient, queryRecipients, addOneRecipient, deleteRecipient } from '@/axios/api/recipients';
import { ElNotification } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
export default function () {
    // 当前页数
    let currentPage4 = ref(1);
    // 每页显示条数
    let pageSize4 = ref(10);
    // 总条数
    let total4 = ref(0);

    // 国家代码
    let country_code = ref('')

    // 国家名称
    let country_name = ref('')

    let recipientsList = ref<any>([]);

    // 每页显示条目个数改变时触发
    const handleSizeChange = () => {
        currentPage4.value = 1;
        queryRecipientsList();
    };

    // 当前页数改变时触发
    const handleCurrentChange = () => {
        queryRecipientsList();
    };

    async function importRecipients() {
        try {
            
            counterStore.flag = true;
            const res: any = await addRecipient();
            queryRecipientsList();
            showMessage(res.code, res.message);
            counterStore.flag = false;
        } catch (err: any) {
            counterStore.flag = false;
            showMessage(err.code, err.message);
        }
      };

    // 查询联系人
    async function queryRecipientsList() {
        try {
            let res: any = await queryRecipients(
                country_code.value,
                country_name.value,
                currentPage4.value,
                pageSize4.value
            );
            if (res.code == 200) {
                recipientsList.value = res.data;
                total4.value = res.total;
                
            } else {
                recipientsList.value = [];
                total4.value = 0;
                showMessage(res.code, res.message);
            }

        } catch (err: any) {
            recipientsList.value = [];
            showMessage(err.code, err.message);
        }
    }
    // 显示通知消息
    function showMessage(type: number, message: string) {
        const title = type === 200 ? 'Success' : 'Error';
        ElNotification({
            title: title,
            message: message,
            type: type === 200 ? 'success' : 'error',
        });
    }


    // 抽屉
    let dialog = ref(false); // 是否显示抽屉
    // 判断点击的是添加还是编辑
    let isEdit = ref(false);
    let recipientsList_data = reactive({
        country_code: '',
        country_name: '',
        yk: '',
        bs: '',
        eu: '',
        hq2:''
    })
    function cancel() {
        dialog.value = false;
    }
    // 添加或编辑收件人
    const handleAdd = (code: string, name: string, yk: string, bs: string, eu: string, hq2: string) => {
        console.log(code)
        if (code == '') {
            isEdit.value = false;
        } else {
            isEdit.value = true;
        }
        recipientsList_data.country_code = '';
        recipientsList_data.country_name = '';
        recipientsList_data.yk = '';
        recipientsList_data.bs = '';
        recipientsList_data.eu = '';
        recipientsList_data.hq2 = '';
        recipientsList_data.country_code = code;
        recipientsList_data.country_name = name;
        recipientsList_data.yk = yk;
        recipientsList_data.bs = bs;
        recipientsList_data.eu = eu;
        recipientsList_data.hq2 = hq2;
        dialog.value = true;
    }

    // 添加收件人提交
    const handleAddsubmit = async (formrecipients: any) => {
        await formrecipients.validate();
        try {
            let res: any = await addOneRecipient(recipientsList_data, isEdit.value);
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            dialog.value = false;
            currentPage4.value = 1;
            queryRecipientsList();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }

    // 抽屉表单校验

    const country_code1 = (_rule: any, value: any, callback: any) => {
        if (/^\d{3}$/.test(value) == false) {
            callback(new Error('国家代码必须为3位为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入国家代码'))
        } else {
            callback() //通过
        }
    }
    const country_code2 = (_rule: any, value: any, callback: any) => {
        // 判断value是否在tableData中
        let flag = false;
        recipientsList.value.forEach((item: any) => {
            if (item.country_code.toLowerCase() === value.toLowerCase()) {
                flag = true;
                return;
            }
        });

        if (flag) {
            callback(new Error('国家代码已存在'))
        } else {
            callback() //通过
        }
    }
    const countryname = (_rule: any, value: any, callback: any) => {
        if (/^\d+$/.test(value)) {
            callback(new Error('国家名称不能为纯数字'))
        } else if (value === '') {
            callback(new Error('请输入国家名称'))
        } else {
            callback() //通过
        }
    }

    const rules = {
        country_code: [
            { validator: country_code1, trigger: 'change' },
            { validator: country_code2, trigger: 'blur' }
        ],
        country_name: [
            { validator: countryname, trigger: 'change' }
        ]

    }
    const rules1 = {
        country_name: [
            { validator: countryname, trigger: 'change' }
        ]
    }

    // 删除收件人
    const handleDelete = async (code: string) => {
        try {
            let res: any = await deleteRecipient(code);
            ElNotification({
                title: 'Success',
                message: res.msg,
                type: 'success',
            });
            currentPage4.value = 1;
            queryRecipientsList();
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
        }
    }

    return {
        currentPage4,
        pageSize4,
        total4,
        country_code,
        country_name,
        recipientsList,
        dialog,
        recipientsList_data,
        rules,
        rules1,
        isEdit,
        cancel,
        handleSizeChange,
        handleCurrentChange,
        importRecipients,
        queryRecipientsList,
        handleAdd,
        handleAddsubmit,
        handleDelete
    }
};